package com.ctgu.chatapp.view.fragment.MainFragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DiffUtil
import com.ctgu.chatapp.databinding.FragmentFriendrequestBinding
import com.ctgu.chatapp.showPojo.FriendQuest
import com.ctgu.chatapp.view.adapter.DiffCallBackForRequest
import com.ctgu.chatapp.view.adapter.RequestAdapter
import com.ctgu.chatapp.viewModel.MainViewModel
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class FriendRequest : Fragment() {

    lateinit var binding: FragmentFriendrequestBinding

    val viewModel by lazy { ViewModelProvider(requireActivity())[MainViewModel::class.java] }

    override

    fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentFriendrequestBinding.inflate(inflater, container, false)
        binding.viewModel = viewModel
        binding.lifecycleOwner = requireActivity()
        initAdapter()
        return binding.root
    }

    private fun initAdapter() {
        var oldList = listOf<FriendQuest>()
        val adapter = RequestAdapter(oldList, parentFragmentManager)
        binding.list.adapter = adapter
        lifecycleScope.launch(IO) {
            viewModel.friendRequestList.collect {
                val result = DiffUtil.calculateDiff(DiffCallBackForRequest(oldList, it), true)
                oldList = it
                withContext(Main) {
                    result.dispatchUpdatesTo(adapter)
                    adapter.data = oldList
                }
            }
        }
    }
}